<script setup lang="ts">
import { AuthAPI } from "@/api/AuthAPI";
import useCountDown from "@/logics/useCountDown";
import { useUserStore } from "@/stores/userStore";
import message from "@/utils/message";
import { toFormValidator } from "@vee-validate/zod";
import { AxiosError } from "axios";
import { ErrorMessage, Field } from "vee-validate";

import * as zod from "zod";
//获取用于存储用户信息的store
const userStore = useUserStore();
//定义表单的验证规则
const validationSchema = toFormValidator(
  zod.object({
    mobile: zod
      .string({
        required_error: "请输入手机号",
        invalid_type_error: "手机号类型错误",
      })
      .regex(/^1[3-9]\d{9}$/, "请输入正确的手机号"),
    code: zod
      .string({
        required_error: "请输入验证码",
      })
      .regex(/^\d{6}$/, "验证码格式错误"),
    isAgree: zod.literal(true, {
      errorMap: () => ({ message: "请勾选同意用户协议" }),
    }),
  })
);
// 创建表单验证对象
const { handleSubmit, values, validateField, setFieldValue } = useForm<{
  mobile: string;
  code: string;
  isAgree: boolean;
}>({
  validationSchema: validationSchema,
});

//实现倒计时
const { count, start, isActive } = useCountDown();

//发送手机码验证
async function sendMsg() {
  //验证手机号是否输入正确
  let { valid } = await validateField("mobile");
  //如果用户没有输入正确格式的手机号，阻止程序继续向下运行
  if (!valid) return;
  //捕获错误
  try {
    //验证通过 发送验证码
    await AuthAPI.sendMsgCodeOfMobileLogin(values.mobile);
    //验证码发送成功
    message({ type: "success", msg: "验证码发送成功" });
  } catch (error) {
    //验证码发送失败
    if (error instanceof AxiosError) {
      message({ type: "error", msg: error.response?.data.message });
    } else {
      message({ type: "error", msg: "验证码发送失败" });
    }
  }
  //正在倒计时 代码停止执行
  if (isActive.value) return;
  try {
    //倒计时
    start(60);
  } catch (error) {}
}

// 表单提交
const onSubmit = handleSubmit((formValue) => {
  // 发送登录请求
  userStore.login(() =>
    AuthAPI.loginByMobileMsgCode(formValue.mobile, formValue.code)
  );
});
</script>
<template>
  <form @submit="onSubmit">
    <Field as="div" name="mobile" v-slot="{ field }" class="form-item">
      <div class="input">
        <i class="iconfont icon-user"></i>
        <input type="text" v-bind="field" placeholder="请输入手机号" />
      </div>
      <ErrorMessage as="div" name="mobile" v-slot="{ message }" class="error">
        <i class="iconfont icon-warning"></i>{{ message }}
      </ErrorMessage>
    </Field>
    <Field as="div" name="code" v-slot="{ field }" class="form-item">
      <div class="input">
        <i class="iconfont icon-code"></i>
        <input type="password" v-bind="field" placeholder="请输入验证码" />
        <span class="code" @click="sendMsg">{{
          isActive ? `剩余${count}秒` : "发送验证码"
        }}</span>
      </div>
      <ErrorMessage as="div" name="code" v-slot="{ message }" class="error">
        <i class="iconfont icon-warning"></i>{{ message }}
      </ErrorMessage>
    </Field>
    <Field as="div" name="isAgree" class="form-item">
      <div class="agree">
        <XtxCheckbox
          :checked="values.isAgree"
          @onChange="
            setFieldValue('isAgree', $event);
            validateField('isAgree');
          "
        />
        <span>我已同意</span>
        <a href="javascript:">《隐私条款》</a>
        <span>和</span>
        <a href="javascript:">《服务条款》</a>
      </div>
      <ErrorMessage name="isAgree" v-slot="{ message }">
        <div class="error">
          <i class="iconfont icon-warning"></i>{{ message }}
        </div>
      </ErrorMessage>
    </Field>
    <button type="submit" class="btn">登录</button>
  </form>
</template>
